/**
 * Created by yangxianming on 2015-04-30.
 * 接受支付宝浏览器登陆二维码图片，并操作手机支付宝实现自动登陆
 */

import models.MyConfig;
import models.ReadProperties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Properties;

// 扩展 HttpServlet 类
@WebServlet(name = "autoLogin", urlPatterns = {"/autoLogin/*"}, loadOnStartup = 2)
public class AutoLogin extends HttpServlet {
    MyConfig myConfig = new MyConfig();
    Properties properties;

    @Override
    public void init(ServletConfig config) throws ServletException {
        ReadProperties readProperties = new ReadProperties(config.getServletContext().getRealPath("/"));
        myConfig.setPropertiesConfig(readProperties);
        myConfig.setAppPath(config.getServletContext().getRealPath("/"));
        this.properties = readProperties.getProperties();
        myConfig.setSplitMark();
        //目前不需要自动登陆，以下先注释掉
        /*
        JFrame jFrame = new JFrame("登陆二维码");
        Point point = new Point(0, 0);
        jFrame.setLocation(point);
        jFrame.setSize(1920, 1080);
        jFrame.setVisible(true);
        myConfig.setjFrame(jFrame);
*/
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //start
        long start = new Date().getTime();

        response.setHeader("Content-type", "text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String returnInfo = "";

        //首字母大写
        char[] cs = request.getPathInfo().substring(1).toCharArray();
        cs[0] -= 32;

        Class<?> action;
        try {
            action = Class.forName("autoLoginBusiness." + String.valueOf(cs));
            Method method = action.getDeclaredMethod("doIt", HttpServletRequest.class, MyConfig.class);
            returnInfo = (String)method.invoke(action.newInstance(), request, myConfig);
        }catch (Exception e){
            e.printStackTrace();
        }

        //end
        long end = new Date().getTime();
        System.out.println(request.getRequestURI() + "; run time: " + (end-start) + "ms");

        out.print(returnInfo);
    }

    public void destroy()
    {
        System.exit(0);
    }

}